package com.juku2024.juku.viewmodel

import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.NetworkUtils
import com.juku2024.juku.R
import com.juku2024.juku.model.AdModel
import com.juku2024.juku.model.CheckResponse
import com.juku2024.juku.network.api.Api
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.network.retrofit.RetrofitUtils
import com.juku2024.juku.request.AdRequest
import com.juku2024.juku.request.CheckAppRequest
import com.juku2024.juku.tools.*
import com.wanban.adutils.AdUtils
import com.wanban.adutils.db.AdRoomUtils
import com.wanban.adutils.db.bean.AdContent
import com.wanban.adutils.db.bean.AdInfo
import com.wanban.adutils.tools.AdConstants
import com.juku2024.juku.BuildConfig
import kotlinx.coroutines.*


class SplashViewModel : BaseViewModel() {



    /**
     * login接口，检查app内容的
     */
    fun checkApp(callback: OnRetrofitResultListener<Boolean>) {
        LogC.e("splash 请求token...")
        doBaseHttp({
            // token超时时间
            val tokenOutTime = SPUtil.instance.tokenExpireTime
            if (System.currentTimeMillis() < tokenOutTime) { // 未超时
                val token = SPUtil.instance.token
                LogC.e("未超时，但是可能需要更新token...")
                return@doBaseHttp if (TextUtils.isEmpty(token)) {
                    null
                } else {    // 保存sKey和iv
                    callback.onSuccess(SPUtil.instance.isAllowPosition)
                    token
                }
            }
            // 超时，直接请求新的
            return@doBaseHttp null
        }, {
            // 已经请求到token
            val appId = AppUtils.method03()
            val appKey = AppUtils.method04()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(
                AppUtils.method05(),
                appId,
                appKey,
                timestamp.toString(),
                AppUtils.method06()
            )
            val request = CheckAppRequest(appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).checkApp(request)
        }, object : OnRetrofitResultListener<CheckResponse> {
            override fun onSuccess(t: CheckResponse) {
                if (t.data == null || t.data?.length != 32) {
                    callback.onFailed(AppUtils.getString(R.string.service_faild))
                    return
                }
                // 更新token超时时间
                updateLocalTokenData(t)

                callback.onSuccess(t.ap)
            }

            override fun onFailed(msg: String) {
                callback.onFailed(msg)
            }
        }, isCheckToken = false)
    }




    /**
     * 获取广告列表
     */
    fun getAdList(callback: OnRetrofitResultListener<List<AdContent>>) {
        var apiVersion = 0L
        doBaseHttp({
            val versionResponse = getVersion(Constants.API_TYPE_NEW_AD)
            apiVersion = versionResponse.apiVersion
            var result: ArrayList<AdContent>?
            return@doBaseHttp if (versionResponse.isUpgrade) { // 需要更新
                null
            } else {
                result = withContext(Dispatchers.IO) { AdRoomUtils.getInstance().adDao().queryList() } as  ArrayList<AdContent>?
                if (result.isNullOrEmpty()) { // 数据为空的时候，也要去查广告
                    result = ArrayList()
                }
                Log.e(AdConstants.TAG,"wbAd -> 广告接口 -> 缓存广告个数：" + result.size)
                callback.onSuccess(result)
                result
            }
        }, {
            val appId = getAppId()
            val appKey = getAppKey()
            val timestamp = getSecondTimestamp()
            val version = apiVersion
            val sign = MD5Utils.getMD5String(version, appId, appKey, timestamp.toString(), getExtra())
            val request = AdRequest(
                version.toString(),
                appId,
                timestamp,
                sign
            )
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getAds(version.toString(), getCommonRequest(request))
        }, object : OnRetrofitResultListener<AdModel> {
            override fun onSuccess(t: AdModel) {
                val list = initAdList(t)
                LogC.e("wbAd -> 广告更新 -> 广告个数：" + list.size)
                if (list.isEmpty()) {
                    if (isNotActive()) return
                    callback.onFailed(AppUtils.getString(R.string.error_net))
                    return
                }
                if (isNotActive()) return
                // 初始化广告计划执行
                callback.onSuccess(list)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                // 初始化广告计划执行
                callback.onFailed(msg)
            }
        })
    }


    private fun initAdList(adModel: AdModel): ArrayList<AdContent> {
        AdUtils.clearAdCache()
        // 测试广告
        changeTestAd(adModel)
        if (adModel.advertising.isNullOrEmpty()) {
            return ArrayList()
        }
        // 重新绑定Reopen广告
        val list = ArrayList<AdContent>()
        adModel.advertising.forEach { entity ->
            if (!entity.advertises.isNullOrEmpty()) {
                val adContent = AdContent()
                adContent.adId = entity.ad_id
                adContent.adType = entity.template
                adContent.adRule = adModel.adInterval
                adContent.countDown = adModel.countDown
                // 广告时间间隔
                adContent.interval = entity.interval
                adContent.plan = adModel.plan
                adContent.adInfo = ArrayList()
                entity.advertises.forEach {
                    val adInfo = AdInfo()
                    adInfo.advertiser = it.advertisers
                    adInfo.ad_type = entity.template
                    adInfo.ad_position = it.advertising_id
                    adInfo.timeout = it.req_timeout
                    adInfo.isCache = it.cache_next
                    adInfo.ad_duration = it.auto_close
                    adInfo.interval = adContent.interval
                    adInfo.adId = entity.ad_id
                    adContent.adInfo.add(adInfo)
                }
                list.add(adContent)
            }
        }
        AdUtils.insertAds(list)
        return list
    }

    private fun changeTestAd(it: AdModel) {
        if (BuildConfig.DEBUG) {
//            if (it.advertising.isNullOrEmpty()) {
//                it.advertising = ArrayList()
//            } else {
                it.advertising?.clear()
//            }

//
//            // 开屏Splash
//            val splashAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            val splashEntity = AdModel.AdvertisingResponse.AdvertisesResponse()
//            splashEntity.advertisers = AdConstants.ADVERTISER_ADMOB
//            splashEntity.advertising_id = "ca-app-pub-8138205203670003/7297538222"
//            splashEntity.cache_next = false
//            splashEntity.req_timeout = 5
//            splashEntity.auto_close = 6
//            splashAdList.add(splashEntity)
//            val splashAd = AdModel.AdvertisingResponse()
//            splashAd.template = AdConstants.ADTYPE_SPLASH
//            splashAd.advertises = splashAdList
//            splashAd.ad_id = AdConstants.AD_ID_OPEN
//            it.advertising.add(splashAd)
////
////
//            // Reopen
//            val reopenAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            val reopenEntity = AdModel.AdvertisingResponse.AdvertisesResponse()
//            reopenEntity.advertisers = AdConstants.ADVERTISER_ADMOB
//            reopenEntity.advertising_id = "ca-app-pub-8138205203670003/7297538222"
//            reopenEntity.cache_next = false
//            reopenEntity.req_timeout = 30
//            reopenEntity.auto_close = 6
//            reopenAdList.add(reopenEntity)
//            val reopenAd = AdModel.AdvertisingResponse()
//            reopenAd.template = AdConstants.ADTYPE_SPLASH
//            reopenAd.advertises = splashAdList
//            reopenAd.ad_id = AdConstants.AD_ID_REOPEN_AD
//            it.advertising.add(reopenAd)
//
//
//            // 详情页插屏
//            val interstitialAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            val adInfoEntity2 = AdModel.AdvertisingResponse.AdvertisesResponse()
//            adInfoEntity2.advertisers = AdConstants.ADVERTISER_IRON_SOURCE
//            adInfoEntity2.advertising_id = "5024156"
//            adInfoEntity2.cache_next = false
//            adInfoEntity2.req_timeout = 6
//            adInfoEntity2.auto_close = 3
//            interstitialAdList.add(adInfoEntity2)
//            val interstitialAdContent = AdModel.AdvertisingResponse()
//            interstitialAdContent.template = AdConstants.ADTYPE_INTERSTITIAL
//            interstitialAdContent.advertises = interstitialAdList
////            interstitialAdContent.interval = 60
//            interstitialAdContent.ad_id = AdConstants.AD_ID_VIDEO_DETAIL_INTERSTITIAL
//            it.advertising.add(interstitialAdContent)
//
            // 暂停native
//            val nativeEntity = AdModel.AdvertisingResponse.AdvertisesResponse()
//            nativeEntity.advertisers = AdConstants.ADVERTISER_ADMOB
//            nativeEntity.advertising_id = "10330691"
//            nativeEntity.cache_next = false
//            nativeEntity.req_timeout = 60
//            nativeEntity.auto_close = 6
//            val nativeAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            nativeAdList.add(nativeEntity)
//            val nativeAd = AdModel.AdvertisingResponse()
//            nativeAd.template = AdConstants.ADTYPE_PAUSE_VIDEO
//            nativeAd.advertises = nativeAdList
//            nativeAd.ad_id = AdConstants.AD_ID_VIDEO_DETAIL_PAUSE
//            it.advertising.add(nativeAd)

//
//            // 详情页剧集列表下方native
//            val detailEntity = AdModel.AdvertisingResponse.AdvertisesResponse()
//            detailEntity.advertisers = AdConstants.ADVERTISER_ADMOB
//            detailEntity.advertising_id = "ca-app-pub-3940256099942544/6300978111"
//            detailEntity.cache_next = false
//            detailEntity.req_timeout = 60
//            detailEntity.auto_close = 6
//            val detailAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            detailAdList.add(detailEntity)
//            val detailAd = AdModel.AdvertisingResponse()
//            detailAd.template = AdConstants.ADTYPE_BANNER
//            detailAd.advertises = detailAdList
//            detailAd.ad_id = AdConstants.AD_ID_VIDEO_DETAIL_BANNER
//            it.advertising.add(detailAd)
//
//
//            // 下载
//            val rewardedAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            val adInfoEntity3 = AdModel.AdvertisingResponse.AdvertisesResponse()
//            adInfoEntity3.advertisers = AdConstants.ADVERTISER_ADMOB
//            adInfoEntity3.advertising_id = "5024152"
//            adInfoEntity3.cache_next = false
//            adInfoEntity3.req_timeout = 30
//            adInfoEntity3.auto_close = 6
//            rewardedAdList.add(adInfoEntity3)
//            val unlockRewardedAd = AdModel.AdvertisingResponse()
//            unlockRewardedAd.template = AdConstants.ADTYPE_INTERSTITIAL
//            unlockRewardedAd.advertises = rewardedAdList
//            unlockRewardedAd.ad_id = AdConstants.AD_ID_DOWNLOAD_REWARD_AD
//            it.advertising.add(unlockRewardedAd)

//            // 解锁
//            val rewardedAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            val adInfoEntity3 = AdModel.AdvertisingResponse.AdvertisesResponse()
//            adInfoEntity3.advertisers = AdConstants.ADVERTISER_IRON_SOURCE
//            adInfoEntity3.advertising_id = "5024152"
//            adInfoEntity3.cache_next = false
//            adInfoEntity3.req_timeout = 15
//            rewardedAdList.add(adInfoEntity3)
//            val unlockRewardedAd = AdModel.AdvertisingResponse()
//            unlockRewardedAd.template = AdConstants.ADTYPE_INTERSTITIAL
//            unlockRewardedAd.advertises = rewardedAdList
//            unlockRewardedAd.ad_id = AdConstants.AD_ID_LOCK_INTERSTITIAL_AD
//            it.advertising.add(unlockRewardedAd)
//
//            // 下载播放插屏
//            val downloadPlayerAdList = ArrayList<AdModel.AdvertisingResponse.AdvertisesResponse>()
//            val downloadPlayerEntity = AdModel.AdvertisingResponse.AdvertisesResponse()
//            downloadPlayerEntity.advertisers = AdConstants.ADVERTISER_IRON_SOURCE
//            downloadPlayerEntity.advertising_id = "10330689"
//            downloadPlayerEntity.cache_next = false
//            downloadPlayerEntity.req_timeout = 10
//            downloadPlayerEntity.auto_close = 6
//            downloadPlayerAdList.add(downloadPlayerEntity)
//            val downloadPlayerAd = AdModel.AdvertisingResponse()
//            downloadPlayerAd.template = AdConstants.ADTYPE_INTERSTITIAL
//            downloadPlayerAd.advertises = downloadPlayerAdList
//            downloadPlayerAd.ad_id = AdConstants.AD_ID_DOWNLOAD_PLAYER_INTERSTITIAL_AD
//            it.advertising.add(downloadPlayerAd)
//
        }
    }


}



